import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'
import Reg from '@/views/Reg/index.vue'
import Layout from '@/views/Layout/index.vue'
import Home from '@/views/Layout/home/index.vue'
import ArtCate from '@/views/Layout/art/art-cate.vue'
import ArtList from '@/views/Layout/art/art-list.vue'
import UserInfo from '@/views/Layout/user/user-info.vue'
import UserAvatar from '@/views/Layout/user/user-avatar.vue'
import UserPwd from '@/views/Layout/user/user-pwd.vue'
import store from '@/store'
Vue.use(VueRouter)
const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/art-cate',
        component: ArtCate
      },
      {
        path: '/art-list',
        component: ArtList
      },
      {
        path: '/user-info',
        component: UserInfo
      },
      {
        path: '/user-avatar',
        component: UserAvatar
      },
      {
        path: '/user-pwd',
        component: UserPwd
      }
    ]
  }
]
const whitePage = ['/reg', '/404', '/login']
const router = new VueRouter({
  routes
})
router.beforeEach(async (to, from, next) => {
  if (store.state.login.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (store.state.login.UserInfo.id) {
        next()
      } else {
        // store
        //   .dispatch('login/getUserInfo')
        //   .then(res => {
        //     next()
        //   })
        //   .catch(err => {
        //     console.log('错误信息', err)
        //   })
        // try {
        await store.dispatch('login/getUserInfo')
        console.log(2)
        next()
        // } catch (err) {
        //   console.log('错误信息', [err])
        //   console.dir(err)
        //   if (err.response.status === 401) {
        //     store.commit('login/logout')
        //     Message.error(err.response.data.message)
        //     console.log(Message.error)
        //     next('/login')
        //   }
        // }
      }
    }
  } else {
    if (whitePage.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + to.path)
    }
  }
})
router.afterEach((to, from) => {
  // to and from are both route objects.
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (locatiion) {
  return originalPush.call(this, locatiion).catch(err => err)
}

export default router
